package com.msb.servicemap.remote;

import com.msb.commons.constant.AmapConstant;
import com.msb.commons.response.ResponseResult;
import com.msb.commons.response.TerminalResponse;
import com.msb.commons.response.TrackResponse;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @Author: chshh
 * @version: 1.0
 */
@Service
public class TrackClient {
    @Autowired
    private RestTemplate restTemplate;

    @Value("${amap.key}")
    private String amapKey;

    @Value("${amap.sid}")
    private String amapSid;

    public ResponseResult add(String tid) {

        StringBuilder urlBuilder = new StringBuilder();

        urlBuilder.append(AmapConstant.TRACK_ADD_URL);
        urlBuilder.append("?");
        urlBuilder.append("key=" + amapKey);
        urlBuilder.append("&");
        urlBuilder.append("sid=" + amapSid);
        urlBuilder.append("&");
        urlBuilder.append("tid=" + tid);

        //调用高德接口
        ResponseEntity<String> entity = restTemplate.postForEntity(urlBuilder.toString(), null, String.class);

        //解析接口

        /*{
            "data": {
                "trid": 100
                "trname": cc
        },
            "errcode": 10000,
            "errdetail": null,
            "errmsg": "OK"
        }*/
        String body = entity.getBody();
        JSONObject jsonObject = JSONObject.fromObject(body);
        JSONObject data = jsonObject.getJSONObject("data");
        //轨迹id
        String trid = data.getString("trid");
        //轨迹名称
        String trname = null;
        if (data.has("trname")){
            trname = data.getString("trname");
        }
        TrackResponse trackResponse = new TrackResponse();
        trackResponse.setTrid(trid);
        trackResponse.setTrname(trname);

        return ResponseResult.success(trackResponse);
    }

}
